﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.Common;
using Nova_Common;
using Nova_DAL;
using System.Data;
using System.Text;
using Nova_MOD;
using Newtonsoft.Json;
using System.Configuration;
using Nova_MOD.ResultModel;
using Nova_Common.Extend;

public partial class DelStorage_SubmitBill : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    DbHelper access = new DbHelper();
    DbHelper dbHelper = new DbHelper();

    Nova_DAL.DbHelper_ERP dbHelper_ERP = new DbHelper_ERP();
    DbCommand cmd = null;
    string strSQL = "";


    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

        }
    }

    protected string getSQL()
    {
        if (ddlS.SelectedValue.ToString() == "0")
        {

            strSQL = "select '入' AA,StockNo, case Bill_Status when 0 then '未完成' else '已完成' end  Bill_Status ,CASE WHEN Async_Status = 0 THEN '未同步' ELSE '已同步' END SyncStatus,CDT,B01,Contents,Small_BillType from TBill_AddStorage  where 1=1";
            if (txtStockNo.Text != "")
            {
                strSQL = strSQL + " AND StockNo like '%" + this.txtStockNo.Text + "%'";
            }
            if (txtDateS.Text != "")
            {
                strSQL = strSQL + " and CDT>='" + txtDateS.Text + "'";
            }
            if (txtDateE.Text != "")
            {
                strSQL = strSQL + " and CDT<= '" + txtDateE.Text + "'";
            }
        }
        else
        {

            strSQL = "select '出' AA,StockNo,case Bill_Status when 0 then '未完成' else '已完成' end as Bill_Status ,CASE WHEN Async_Status = 0 THEN '未同步' ELSE '已同步' END SyncStatus,CDT,B01,Contents,Small_BillType from TBill_DelStorage  where 1=1";
            if (txtStockNo.Text != "")
            {
                strSQL = strSQL + " AND StockNo like '%" + this.txtStockNo.Text + "%'";
            }
            if (txtDateS.Text != "")
            {
                strSQL = strSQL + " and CDT>='" + txtDateS.Text + "'";
            }
            if (txtDateE.Text != "")
            {
                strSQL = strSQL + " and CDT<= '" + txtDateE.Text + "'";
            }

        }
        if (ddlSyncMes.SelectedValue != "-1")
        {
            strSQL = strSQL + " AND Async_Status = " + ddlSyncMes.SelectedValue + "";
        }

        if (cobDueState.SelectedValue != "-1")
        {
            strSQL += " AND Bill_Status = '" + cobDueState.SelectedValue + "'";
        }
        else
        {
            strSQL += " AND Bill_Status <>2";

        }
        strSQL = strSQL + " order by CDT DESC";
        return strSQL;
    }

    protected void bind()
    {
        cmd = access.GetSqlStringCommond(getSQL());
        gvStock.DataSource = access.ExecuteDataSet(cmd);
        gvStock.DataBind();
    }



    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        lbMsg.Text = "";
        gv.DataSource = null;
        gv.DataBind();
        gvStock.DataSource = null;
        gvStock.DataBind();
        bind();

    }

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            if (decimal.Parse(e.Row.Cells[2].Text) != decimal.Parse(e.Row.Cells[3].Text))
            {
                e.Row.BackColor = System.Drawing.Color.FromName("#cecece");
            }
        }
    }


    protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        string StockNo = "";
        StringBuilder sbMsg = new StringBuilder();
        int checkCount = 0;
        for (int i = 0; i < gvStock.Rows.Count; i++)
        {
            CheckBox chkSelect = (CheckBox)gvStock.Rows[i].Cells[0].FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                checkCount += 1;
                StockNo = gvStock.DataKeys[i].Value.ToString();

                if (this.ddlS.SelectedIndex == 0)
                {
                    strSQL = "SELECT * FROM TBill_AddStorage WHERE  StockNo = '" + StockNo + "'";
                    cmd = access.GetSqlStringCommond(strSQL);
                    ds = access.ExecuteDataSet(cmd);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (ds.Tables[0].Rows[0]["Bill_Status"].ToString() == "1")
                        {
                            sbMsg.Append("入库单" + StockNo + "已经被处理过，无需再处理！");
                            break;
                        }
                        else
                        {
                            string sqlStr = string.Format(@"SELECT COUNT(PID) FROM dbo.TAddStorage_List WHERE StockNo='{0}' AND Num > Act_Num ", StockNo);
                            cmd = access.GetSqlStringCommond(sqlStr);
                            object obj = access.ExecuteScalar(cmd);
                            int n = int.Parse(obj.ToString());
                            if (n > 0)
                            {
                                sbMsg.Append("入库单" + StockNo + "中单据物料明细还没有完成入库，暂无法完成单据！");
                                break;
                            }

                            strSQL = "UPDATE TBill_AddStorage SET Bill_Status = '1' Where StockNo = '" + StockNo + "'";
                            cmd = access.GetSqlStringCommond(strSQL);
                            int j = (int)access.ExecuteNonQuery(cmd);
                        }
                    }
                    else
                    {
                        sbMsg.Append("入库单号" + StockNo + "不存在，请查证后再处理！");
                        break;
                    }
                }
                else
                {
                    try
                    {
                        //if (checkBillState(StockNo) == true)
                        //{
                        //    lbMsg.Text = "该单据已经提交，无需再次提交";
                        //    return;
                        //}
                        //sendToSAP(StockNo);

                        strSQL = "SELECT * FROM TBill_DelStorage WHERE  StockNo = '" + StockNo + "'";
                        cmd = access.GetSqlStringCommond(strSQL);
                        ds = access.ExecuteDataSet(cmd);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            if (ds.Tables[0].Rows[0]["Bill_Status"].ToString() == "1")
                            {
                                sbMsg.Append("出库单" + StockNo + "已经被处理过，无需再处理！");
                                break;
                            }
                            else
                            {
                                string sqlStr = string.Format(@"SELECT COUNT(PID) FROM dbo.TDelStorage_List WHERE StockNo='{0}' AND Num > Act_Num ", StockNo);
                                cmd = access.GetSqlStringCommond(sqlStr);
                                object obj = access.ExecuteScalar(cmd);
                                int n = int.Parse(obj.ToString());
                                if (n > 0)
                                {
                                    sbMsg.Append("出库单" + StockNo + "中单据物料明细还没有完成出库，暂无法完成单据！");
                                    break;
                                }

                                strSQL = "UPDATE TBill_DelStorage SET Bill_Status = '1' Where StockNo = '" + StockNo + "'";
                                cmd = access.GetSqlStringCommond(strSQL);
                                int j = (int)access.ExecuteNonQuery(cmd);
                                if (j > 0)
                                {
                                    //xgw 注销 有关ERP的部分内容
                                    //strSQL = "SELECT DocNo FROM ERP_WMS_CRK WHERE DocNo='" + StockNo + "'";
                                    //cmd = access.GetSqlStringCommond(strSQL);
                                    //DataSet DS_E = access.ExecuteDataSet(cmd);
                                    //if (DS_E.Tables[0].Rows.Count > 0)
                                    //{
                                    //    //反馈
                                    //    strSQL = @"UPDATE ERP_WMS_CRK SET ExcuteState=2,fksj='" + DateTime.Now.ToString() + "' WHERE DocNo='" + StockNo + "'";
                                    //    cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
                                    //    dbHelper_ERP.ExecuteNonQuery(cmd);
                                    //}
                                }
                            }
                        }
                        else
                        {
                            sbMsg.Append("出库单号" + StockNo + "不存在，请查证后再处理！");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.ToString());
                        return;
                    }
                }
            }
        }

        if (checkCount == 0)
        {
            ShowBox.MessageBox(this.Page, "请选择要处理的单据！");
            return;
        }
        else
        {
            if (sbMsg.Length == 0)
            {
                ShowBox.MessageBox(this.Page, "操作成功！");

                bind();
                gv.DataSource = null;
                gv.DataBind();
            }
            else
            {
                ShowBox.MessageBox(this.Page, sbMsg.ToString());

            }
        }
    }



    private Boolean checkBillState(String StockNo)
    {
        bool val = false;
        try
        {
            String sql = "select top 1 Bill_Status from TBill_DelStorage where StockNo='" + StockNo + "'";
            DbCommand cmd = null;
            cmd = access.GetSqlStringCommond(sql);
            object result = access.ExecuteScalar(cmd);
            if (int.Parse(result.ToString()) == 1)
            {
                val = true;
            }
            else
            {
                val = false;
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }
        return val;

    }

    //校验该单据号下面是否存在计划数量和实际数量不一致的
    //private Boolean checkNum(String StockNo)
    //{
    //    bool val = false;
    //    try
    //    {
    //        String sql = " select top 1 1 from TDelStorage_List where Num<>Act_Num And StockNo='" + StockNo + "'";
    //        DbCommand cmd = null;
    //        cmd = access.GetSqlStringCommond(sql);
    //        object result = access.ExecuteScalar(cmd);
    //        if (result == null)
    //        {
    //            val = true;
    //        }
    //        else
    //        {
    //            val = false;
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        Console.Write(ex.ToString());
    //    }
    //    return val;

    //}

    private Boolean sendToSAP(String StockNo)
    {
        //        SI_gi_result_lw_tjService sapservice = new SI_gi_result_lw_tjService();
        bool val = false;
        try
        {
            //            strSQL = @"Select TDL.W01,TDL.StockNo,TDL.WN01,TDL.Mat_Code,TDL.Num,TDL.Act_Num,TDL.S01,TDL.S02,
            //                              TDL.S03,TDL.S04,TDL.S05,TDL.TS01,TDL.TS02,TDL.TS03,TDL.TS04,TDL.TS05,TDL.W02,
            //                              TDL.W03,TDL.W04,TDL.W05,TDL.W06,TDL.W07,TDL.W08,TBD.OID
            //                       From TDelStorage_List TDL
            //                       Left outer join TBill_DelStorage TBD on TDL.StockNo=TBD.StockNo
            //                       Where TDL.StockNo='" + StockNo + "'";
            //            DbCommand cmd = null;
            //            DataSet ds = new DataSet();
            //            DataTable dt = new DataTable();
            //            cmd = access.GetSqlStringCommond(strSQL);
            //            ds = access.ExecuteDataSet(cmd);
            //            dt = ds.Tables[0];
            //            if (dt.Rows.Count > 0)
            //            {

            //                int j = dt.Rows.Count;
            //                DT_gi_result_lw_tjROW[] outbillStruct = new DT_gi_result_lw_tjROW[j];
            //                //组装结构体
            //                for (int i = 0; i < dt.Rows.Count; i++)
            //                {
            //                    DT_gi_result_lw_tjROW row = new DT_gi_result_lw_tjROW();
            //                    row.seq_no = dt.Rows[i]["StockNo"].ToString();
            //                    row.document_no = dt.Rows[i]["W01"].ToString();
            //                    row.item_no = dt.Rows[i]["WN01"].ToString();
            //                    row.movement_type = dt.Rows[i]["W02"].ToString();
            //                    row.special_indicator = dt.Rows[i]["S01"].ToString();
            //                    row.order_number = dt.Rows[i]["S02"].ToString();
            //                    row.part_no = dt.Rows[i]["Mat_Code"].ToString();
            //                    row.company = dt.Rows[i]["W03"].ToString();
            //                    row.valuation_type = dt.Rows[i]["TS02"].ToString();
            //                    row.storage_loc = dt.Rows[i]["S05"].ToString();
            //                    row.lot_batch_no = dt.Rows[i]["S03"].ToString();
            //                    row.vendor_no = dt.Rows[i]["W04"].ToString();
            //                    row.po_no = dt.Rows[i]["W05"].ToString();
            //                    row.plan_quantity = dt.Rows[i]["Num"].ToString();
            //                    row.issue_date = dt.Rows[i]["W06"].ToString();
            //                    row.issue_time = dt.Rows[i]["W07"].ToString();
            //                    row.entry_user = dt.Rows[i]["W08"].ToString();
            //                    row.actual_quantity = dt.Rows[i]["Act_Num"].ToString();
            //                    row.actual_wms_date = DateTime.Now.Date.ToString();
            //                    row.actual_wms_time = DateTime.Now.ToString("hh:mm:ss");
            //                    row.wms_entry_user = dt.Rows[i]["OID"].ToString();
            //                    outbillStruct[i] = row;
            //                }

            //                //提交给SAP
            //                sapservice.SI_gi_result_lw_tj(outbillStruct);
            //            }
            //            cmd.Dispose();
            //            ds.Dispose();
            //更改单据状态
            changeBillStatus(StockNo);
            val = true;
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
            val = false;
            return val;
        }

        return val;

    }


    private void changeBillStatus(String StockNo)
    {
        try
        {
            String sql = "update TBill_DelStorage set Bill_Status=1 where StockNo='" + StockNo + "'";
            DbCommand cmd = null;
            cmd = access.GetSqlStringCommond(sql);
            int i = access.ExecuteNonQuery(cmd);
            if (i > 0)
            {
                lbMsg.Text = "提交成功";
            }
            else
            {
                lbMsg.Text = "单据未找到";
            }
        }
        catch (Exception ex)
        {
            Console.Write(ex.ToString());
        }

    }

    //protected void ibtn_Click(object sender, ImageClickEventArgs e)
    //{

    //for (int i = 0; i < gv.Rows.Count; i++)
    //{
    //    CheckBox chkSelect = (CheckBox)gv.Rows[i].Cells[0].FindControl("chkSelect");
    //    if (chkSelect.Checked)
    //    {
    //        if (Convert.ToDecimal(gv.Rows[i].Cells[4].Text) != 0)
    //        {
    //            lbMsg.Text = "此单据明细已处理过，不能做作废处理！";
    //            return;
    //        }
    //        else
    //        {
    //            if (ddlS.SelectedIndex==0)
    //            {
    //                strSQL = "UPDATE TAddStorage_List SET Add_Flag2 = '1' WHERE PID = '" + gv.DataKeys[i].Value.ToString() + "'";
    //                cmd = access.GetSqlStringCommond(strSQL);
    //                int iflag = access.ExecuteNonQuery(cmd);
    //                if (iflag <= 0)
    //                {
    //                    lbMsg.Text = "作废处理操作失败！";
    //                    return;
    //                }

    //            }
    //        }
    //    }
    //}
    //}


    protected void gvStock_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gvStock.PageIndex = e.NewPageIndex;
        bind();

    }
    protected void gvStock_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid(gvStock.DataKeys[gvStock.SelectedIndex].Value.ToString());

    }

    private void BindGrid(string strStockNo)
    {
        if (this.ddlS.SelectedIndex == 1)
        {
            strSQL = @"Select TDL.PID,TDL.W01,TDL.StockNo,TDL.WN01,TDL.Mat_Code,ISNULL(TDL.Num,0) as Num,ISNULL(TDL.Act_Num,0) as Act_Num,TDL.S01,TDL.S02,
                                  TDL.S03,TDL.S04,TDL.S05,TDL.TS01,TDL.TS02,TDL.TS03,TDL.TS04,TDL.TS05,TDL.W02,
                                  TDL.W03,TDL.W04,TDL.W05,TDL.W06,TDL.W07,TDL.W08,TBD.Bill_Status
                           From TDelStorage_List TDL
                           Left outer join TBill_DelStorage TBD on TDL.StockNo=TBD.StockNo where 1=1 ";
            strSQL += " and TDL.StockNo = '" + strStockNo + "'";
            strSQL += " ORDER BY TDL.CDT DESC";
        }
        else
        {
            strSQL = @"Select TDL.PID,TDL.V01 AS W01,TDL.StockNo,TDL.VN01 AS WN01,TDL.Mat_Code,ISNULL(TDL.Num,0) as Num,ISNULL(TDL.Act_Num,0) as Act_Num,
                                  TDL.S01,TDL.S02,
                                  TDL.S03,TDL.S04,TDL.S05,TDL.TS01,TDL.TS02,TDL.TS03,TDL.TS04,TDL.TS05,TDL.V02 AS W02,
                                  TDL.V03 AS W03,TDL.V04 W04,TDL.V05 W05,TDL.V06 W06,TDL.V07 W07,TDL.V08 W08,TBD.Bill_Status
                           From TAddStorage_List TDL
                           Left outer join TBill_AddStorage TBD on TDL.StockNo=TBD.StockNo where 1=1 ";
            strSQL += " and TDL.StockNo = '" + strStockNo + "'";
            strSQL += " ORDER BY TDL.CDT DESC";
        }
        cmd = access.GetSqlStringCommond(strSQL);
        gv.DataSource = access.ExecuteDataSet(cmd);
        gv.DataBind();
    }


    //作废就是删除(入出库明细单和入出库单都要删除)
    protected void ibtnDelete_Click(object sender, ImageClickEventArgs e)
    {
        int iCount = 0;
        int iFlag = 0;
        for (int i = 0; i < this.gvStock.Rows.Count; i++)
        {
            CheckBox box = (CheckBox)this.gvStock.Rows[i].Cells[0].FindControl("chkSelect");
            if (box.Checked)
            {

                using (Trans s = new Trans())
                {
                    if (this.ddlS.SelectedIndex == 0)
                    {

                        try
                        {
                            iCount = Del_Info(s, this.gvStock.DataKeys[i].Value.ToString());

                            Delete_MainInfor(iCount, s, this.gvStock.DataKeys[i].Value.ToString());

                            s.Commit();
                            iFlag = 1;
                        }

                        catch (Exception ex)
                        {
                            iFlag = 0;
                            s.RollBack();
                            ShowBox.MessageBox(this.Page, "删除入库订单信息表事务操作异常跳出！");
                            return;
                        }
                    }
                    else if (this.ddlS.SelectedIndex == 1)
                    {
                        try
                        {
                            iCount = Del_Outfo(s, this.gvStock.DataKeys[i].Value.ToString());

                            Delete_MainOutfor(iCount, s, this.gvStock.DataKeys[i].Value.ToString());

                            s.Commit();
                            iFlag = 1;
                        }

                        catch (Exception ex)
                        {
                            iFlag = 0;
                            s.RollBack();
                            ShowBox.MessageBox(this.Page, "删除出库订单信息表事务操作异常跳出！");
                            return;
                        }
                    }

                }
            }
        }
        if (iFlag == 1)
        {
            ShowBox.MessageBox(this.Page, "单据删除成功！");
            return;
        }
        this.lbMsg.Text = "操作成功";


    }



    /// <summary>
    /// 删除入库单明细信息
    /// </summary>
    /// <param name="s"></param>
    /// <param name="strStockNo"></param>
    /// <returns></returns>
    protected int Del_Info(Trans s, string strStockNo)
    {
        int iCount = 0;
        strSQL = "Select StockNo From TAddStorage_List where StockNo = '" + strStockNo.Trim() + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataSet ds_Add = dbHelper.ExecuteDataSet(cmd);
        if (ds_Add.Tables[0].Rows.Count < 0)
        {
            iCount = -1;//订单编号存在
        }
        else
        {
            strSQL = "DELETE TAddStorage_List  WHERE  StockNo= '" + strStockNo.Trim() + "'";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            if (s == null)
            {
                dbHelper.ExecuteNonQuery(cmd);
            }
            else
            {
                dbHelper.ExecuteNonQuery(cmd, s);
            }
        }
        return iCount;
    }


    /// <summary>
    /// 删除入库单主表明细
    /// </summary>
    /// <param name="iCount"></param>
    /// <param name="t"></param>
    /// <param name="strStockNo"></param>
    public void Delete_MainInfor(int iCount, Trans t, string strStockNo)
    {

        strSQL = "DELETE TBill_AddStorage  WHERE  StockNo= '" + strStockNo.Trim() + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        if (t == null)
        {
            dbHelper.ExecuteNonQuery(cmd);
        }
        else
        {
            dbHelper.ExecuteNonQuery(cmd, t);
        }
    }

    /// <summary>
    /// 删除出库单明细信息
    /// </summary>
    /// <param name="s"></param>
    /// <param name="strStockNo"></param>
    /// <returns></returns>
    protected int Del_Outfo(Trans s, string strStockNo)
    {
        int iCount = 0;
        strSQL = "Select StockNo From TDelStorage_List where StockNo = '" + strStockNo.Trim() + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        DataSet ds_Add = dbHelper.ExecuteDataSet(cmd);
        if (ds_Add.Tables[0].Rows.Count < 0)
        {
            iCount = -1;//订单编号存在
        }
        else
        {
            strSQL = "DELETE TDelStorage_List  WHERE  StockNo= '" + strStockNo.Trim() + "'";
            cmd = dbHelper.GetSqlStringCommond(strSQL);
            if (s == null)
            {
                dbHelper.ExecuteNonQuery(cmd);
            }
            else
            {
                dbHelper.ExecuteNonQuery(cmd, s);
            }
        }
        return iCount;
    }

    /// <summary>
    /// 删除出库单主表信息
    /// </summary>
    /// <param name="iCount"></param>
    /// <param name="t"></param>
    /// <param name="strStockNo"></param>
    public void Delete_MainOutfor(int iCount, Trans t, string strStockNo)
    {

        strSQL = "DELETE TBill_DelStorage  WHERE  StockNo= '" + strStockNo.Trim() + "'";
        cmd = dbHelper.GetSqlStringCommond(strSQL);
        if (t == null)
        {
            dbHelper.ExecuteNonQuery(cmd);
        }
        else
        {
            dbHelper.ExecuteNonQuery(cmd, t);
        }
    }


    protected void gvStock_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            LinkButton lbtn_StockNo = (LinkButton)e.Row.FindControl("lbtn_StockNo");
            string[] arrayData = lbtn_StockNo.CommandArgument.ToString().Split('|');
            string stockNo = arrayData[0];
            string type = arrayData[1];
            string createType = arrayData[2];

            string str = string.Format("javascript:document.getElementById('{1}').value=window.open('UnDelDataList.aspx?Ram=" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "&strStockNo={0}&type={2}', window, 'Height=500px,Width=1200px,top=250, left=240, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');document.URL=location.href;void(0);",
            stockNo, hidden.ClientID, type);
            lbtn_StockNo.Attributes.Add("onclick", str);

            Label lbMesStatus = (Label)e.Row.FindControl("lbMesStatus");
            LinkButton lbSyncMes = (LinkButton)e.Row.FindControl("lbSyncMes");
            if (lbMesStatus.Text == "未同步")
            {
                lbSyncMes.Visible = true;
            }
            else
            {
                lbSyncMes.Visible = false;
            }
            if (createType == "0")
            {
                lbSyncMes.Visible = false;
            }

        }
    }

    protected void ibtnCancel_Click(object sender, ImageClickEventArgs e)
    {
        string StockNo = "";
        StringBuilder sbMsg = new StringBuilder();
        int checkCount = 0;
        for (int i = 0; i < gvStock.Rows.Count; i++)
        {
            CheckBox chkSelect = (CheckBox)gvStock.Rows[i].Cells[0].FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                checkCount += 1;
                StockNo = gvStock.DataKeys[i].Value.ToString();

                if (this.ddlS.SelectedIndex == 0)
                {
                    strSQL = "SELECT * FROM TBill_AddStorage WHERE  StockNo = '" + StockNo + "'";
                    cmd = access.GetSqlStringCommond(strSQL);
                    ds = access.ExecuteDataSet(cmd);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (ds.Tables[0].Rows[0]["Bill_Status"].ToString() == "0")
                        {
                            sbMsg.Append("入库单" + StockNo + "未被处理过，无需撤销处理！");
                            break;
                        }
                        else
                        {
                            strSQL = "UPDATE TBill_AddStorage SET Bill_Status = '0' Where StockNo = '" + StockNo + "'";
                            cmd = access.GetSqlStringCommond(strSQL);
                            int j = (int)access.ExecuteNonQuery(cmd);
                            if (j > 0)
                            {

                                //xgw 注销 有关ERP的部分内容
                                //strSQL = "SELECT DocNo FROM ERP_WMS_CRK WHERE DocNo='" + StockNo + "'";
                                //cmd = access.GetSqlStringCommond(strSQL);
                                //DataSet DS_E = access.ExecuteDataSet(cmd);
                                //if (DS_E.Tables[0].Rows.Count > 0)
                                //{
                                //    //反馈
                                //    strSQL = @"UPDATE ERP_WMS_CRK SET ExcuteState=2,fksj='" + DateTime.Now.ToString() + "' WHERE DocNo='" + StockNo + "'";
                                //    cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
                                //    dbHelper_ERP.ExecuteNonQuery(cmd);
                                //}
                            }
                        }
                    }
                    else
                    {
                        sbMsg.Append("入库单号" + StockNo + "不存在，请查证后再处理！");
                        break;
                    }
                }
                else
                {
                    try
                    {
                        //if (checkBillState(StockNo) == true)
                        //{
                        //    lbMsg.Text = "该单据已经提交，无需再次提交";
                        //    return;
                        //}
                        //sendToSAP(StockNo);

                        strSQL = "SELECT * FROM TBill_DelStorage WHERE  StockNo = '" + StockNo + "'";
                        cmd = access.GetSqlStringCommond(strSQL);
                        ds = access.ExecuteDataSet(cmd);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            if (ds.Tables[0].Rows[0]["Bill_Status"].ToString() == "0")
                            {
                                sbMsg.Append("出库单" + StockNo + "未被处理过，无需撤销处理！");
                                break;
                            }
                            else
                            {
                                strSQL = "UPDATE TBill_DelStorage SET Bill_Status = '0' Where StockNo = '" + StockNo + "'";
                                cmd = access.GetSqlStringCommond(strSQL);
                                int j = (int)access.ExecuteNonQuery(cmd);
                                if (j > 0)
                                {
                                    //xgw 注销 有关ERP的部分内容
                                    //strSQL = "SELECT DocNo FROM ERP_WMS_CRK WHERE DocNo='" + StockNo + "'";
                                    //cmd = access.GetSqlStringCommond(strSQL);
                                    //DataSet DS_E = access.ExecuteDataSet(cmd);
                                    //if (DS_E.Tables[0].Rows.Count > 0)
                                    //{
                                    //    //反馈
                                    //    strSQL = @"UPDATE ERP_WMS_CRK SET ExcuteState=2,fksj='" + DateTime.Now.ToString() + "' WHERE DocNo='" + StockNo + "'";
                                    //    cmd = dbHelper_ERP.GetSqlStringCommond(strSQL);
                                    //    dbHelper_ERP.ExecuteNonQuery(cmd);
                                    //}
                                }
                            }
                        }
                        else
                        {
                            sbMsg.Append("出库单号" + StockNo + "不存在，请查证后再处理！");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.ToString());
                        return;
                    }
                }
            }
        }

        if (checkCount == 0)
        {
            ShowBox.MessageBox(this.Page, "请选择要处理的单据！");
            return;
        }
        else
        {
            if (sbMsg.Length == 0)
            {
                ShowBox.MessageBox(this.Page, "操作成功！");

                bind();
                gv.DataSource = null;
                gv.DataBind();
            }
            else
            {
                ShowBox.MessageBox(this.Page, sbMsg.ToString());

            }
        }
    }

    protected void lbSyncMes_Click(object sender, EventArgs e)
    {
        LinkButton lbMesStatus = (LinkButton)sender;
        string[] arraySyncMes = lbMesStatus.CommandArgument.ToString().Split('|');
        string stockNo = arraySyncMes[0];
        string type = arraySyncMes[1];
        string stockStatus = arraySyncMes[2];
        string small_BillType = arraySyncMes[3];
        int row = 0;
        if (stockStatus == "未完成")
        {
            ShowBox.MessageBox(this.Page, "【同步MES】先单据完成确认，再同步单据到MES!");
            return;
        }
        if (type == "入")
        {
            MesApiResult res = SyncAddStorageToMes(stockNo);
            if (res.code == 0)
            {
                strSQL = "UPDATE dbo.TBill_AddStorage SET Async_Status = 1 WHERE StockNo='" + stockNo + "'";
                cmd = access.GetSqlStringCommond(strSQL);
                row = access.ExecuteNonQuery(cmd);
                if (row > 0)
                {
                    bind();
                    ShowBox.MessageBox(this.Page, "【同步MES】同步入库单到MES系统成功!");
                    //lbMsg.Text = "【同步MES】同步入库单到MES系统成功!";
                }
                else
                {
                    ShowBox.MessageBox(this.Page, "【同步MES】调用同步接口后，WMS更新入库单据状态出错!");
                    //lbMsg.Text = "【同步MES】调用同步接口后，WMS更新入库单据状态出错!";
                }
            }
            else if (res.code == -1)
            {
                lbMsg.Text = res.msg;
            }
            else
            {
                lbMsg.Text = res.msg;
            }
        }
        else
        {
            MesApiResult res = SyncDelStorageToMes(stockNo, small_BillType);
            if (res.code == 0)
            {
                strSQL = "UPDATE dbo.TBill_DelStorage SET Async_Status = 1 WHERE StockNo='" + stockNo + "'";
                cmd = access.GetSqlStringCommond(strSQL);
                row = access.ExecuteNonQuery(cmd);
                if (row > 0)
                {
                    bind();
                    ShowBox.MessageBox(this.Page, "【同步MES】同步出库单到MES系统成功!");
                    // lbMsg.Text = "【同步MES】同步出库单到MES系统成功!";
                }
                else
                {
                    ShowBox.MessageBox(this.Page, "【同步MES】调用同步接口后，WMS更新出库单据状态出错!");
                    // lbMsg.Text = "【同步MES】调用同步接口后，WMS更新出库单据状态出错!";
                }
            }
            else if (res.code == -1)
            {
                ShowBox.MessageBox(this.Page, res.msg);
                //lbMsg.Text = res.msg;
            }
            else
            {
                ShowBox.MessageBox(this.Page, res.msg);
                // lbMsg.Text = res.msg;
            }

        }

    }

    private MesApiResult SyncAddStorageToMes(string stockNo)
    {
        strSQL = @"SELECT TAS.StockNo,TAL.Mat_Code,TBM.Mat_Name,TBM.Unit_Base,TBM.S01,TAL.TS01,TAL.S05,TAL.Num,TAL.Act_Num,TAS.S03,TAS.S04
                FROM dbo.TBill_AddStorage TAS INNER JOIN dbo.TAddStorage_List TAL
                ON TAS.StockNo = TAL.StockNo INNER JOIN dbo.TBase_Material TBM ON TAL.Mat_Code = TBM.Mat_Code
                WHERE TAL.StockNo='" + stockNo + "'";
        cmd = access.GetSqlStringCommond(strSQL);
        DataTable dt = access.ExecuteDataTable(cmd);
        List<SyncAddStorageMesModel> paramModelList = new List<SyncAddStorageMesModel>();
        if (dt.Rows.Count > 0)
        {
            if (decimal.Parse(dt.Rows[0]["Act_Num"].ToString()) <= 0)
                return new MesApiResult() { code = -1, msg = "【同步MES】入库单据入库数量为0,还没有入库!" };
            SyncAddStorageMesModel paramModel = new SyncAddStorageMesModel();
            paramModel.mr_no = dt.Rows[0]["StockNo"].ToString();
            paramModel.part_no = dt.Rows[0]["Mat_Code"].ToString();
            paramModel.part_name = dt.Rows[0]["Mat_Name"].ToString();
            paramModel.part_unit = dt.Rows[0]["Unit_Base"].ToString();
            paramModel.part_spec = dt.Rows[0]["S01"].ToString();
            paramModel.vendor_name = dt.Rows[0]["S04"].ToString();
            paramModel.quantity = decimal.Parse(dt.Rows[0]["Act_Num"].ToString());
            paramModel.po_no = dt.Rows[0]["S05"].ToString();
            paramModel.notice_no = dt.Rows[0]["TS01"].ToString();
            paramModel.create_time = DateExtend.GetTimeStamp(DateTime.Now);
            paramModelList.Add(paramModel);
            try
            {
                string mesApi = ConfigurationManager.AppSettings["MesAddStorageStockApi"].ToString();
                string result = HttpMethods.HttpPost(mesApi, paramModelList.ToJson());
                MesApiResult res = Json.ToObject<MesApiResult>(result);
                return res;
            }
            catch (Exception ex)
            {
                return new MesApiResult() { code = -1, msg = string.Format("【同步MES】{0}", "MES 远程服务器无法连接!") };
            }

        }
        else
        {
            return new MesApiResult() { code = -1, msg = "【同步MES】WMS同步的时候没有获取到收料单数据!" };
        }
    }

    private MesApiResult SyncDelStorageToMes(string stockNo, string small_BillType)
    {
        strSQL = @"SELECT TSL.StockNo,TSL.Mat_Code,TBM.Mat_Name,TBM.Unit_Base,TBM.S01, TBM.TM01,TBM.TM02,TBM.TM03,TSL.TS01,TSL.Num,TSL.Act_Num
                FROM  dbo.TDelStorage_List TSL INNER JOIN dbo.TBase_Material TBM ON TSL.Mat_Code = TBM.Mat_Code
                WHERE TSL.StockNo='" + stockNo + "'";
        cmd = access.GetSqlStringCommond(strSQL);
        DataTable dt = access.ExecuteDataTable(cmd);
        List<SyncDelStorageMesModel> paramModelList = new List<SyncDelStorageMesModel>();
        if (dt.Rows.Count > 0)
        {
            MainData mainData = new MainData()
            {
                material_requisition_no = dt.Rows[0]["StockNo"].ToString(),
                notice_no = dt.Rows[0]["TS01"].ToString(),
                create_time = DateExtend.GetTimeStamp(DateTime.Now)
            };
            List<DetailModel> detailList = new List<DetailModel>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DetailModel detail = new DetailModel();
                detail.part_no = dt.Rows[i]["Mat_Code"].ToString();
                detail.part_name = dt.Rows[i]["Mat_Name"].ToString();
                detail.part_spec = dt.Rows[i]["S01"].ToString();
                detail.material = dt.Rows[i]["TM01"].ToString();
                detail.out_diam = dt.Rows[i]["TM02"].ToString();
                detail.length = dt.Rows[i]["TM03"].ToString();
                detail.qty = (small_BillType == "11")
                             ? decimal.Parse(dt.Rows[i]["Act_Num"].ToString())
                             : decimal.Parse(dt.Rows[i]["Num"].ToString());
                detailList.Add(detail);
            }
            SyncDelStorageMesModel paramModel = new SyncDelStorageMesModel()
            {
                main = mainData,
                details = detailList
            };
            paramModelList.Add(paramModel);
            try
            {
                string mesApi = ConfigurationManager.AppSettings["MesDelStorageStockApi"].ToString();
                string result = HttpMethods.HttpPost(mesApi, paramModelList.ToJson());
                MesApiResult res = Json.ToObject<MesApiResult>(result);
                return res;
            }
            catch (Exception ex)
            {
                return new MesApiResult() { code = -1, msg = string.Format("【同步MES】{0}", "MES 远程服务器无法连接!") };
            }
        }
        else
        {
            return new MesApiResult() { code = -1, msg = "【同步MES】WMS同步的时候没有获取到领料单数据!" };
        }
    }

    protected void ibt_UserComplete_Click(object sender, EventArgs e)
    {
        StringBuilder errMsg = new StringBuilder();
        int chkCount = 0;
        for (int i = 0; i < gvStock.Rows.Count; i++)
        {
            CheckBox chkSelect = (CheckBox)gvStock.Rows[i].Cells[0].FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                chkCount++;
                string stockNo = gvStock.DataKeys[i].Value.ToString();
                string stockType = gvStock.Rows[i].Cells[3].Text.ToString();
                if (stockType == "入")
                {
                    errMsg.Append("线下人工拣选出库只针对出库单据!");
                    break;
                }
                else
                {
                    if (stockNo.Substring(0, 2) == "EB")
                    {
                        errMsg.AppendFormat("线下人工拣选出库完成只针对MES出库单据，EB开头的单据是WMS系统单!", stockNo);
                        break;
                    }
                    string content = gvStock.Rows[i].Cells[6].Text.ToString().Replace("&nbsp;", "");
                    string small_BillType = gvStock.Rows[i].Cells[4].Text.ToString();
                    if (!string.IsNullOrWhiteSpace(content))
                    {
                        errMsg.AppendFormat("出库单:{0}已经被线下人工拣选出库完成!", stockNo);
                        break;
                    }
                    if (small_BillType == "已完成")
                    {
                        errMsg.AppendFormat("出库单:{0}单据状态已经完成，无法再对单据人工线下拣选出库完成!", stockNo);
                        break;
                    }
                    string strSql = string.Format(@"SELECT COUNT(PID) FROM dbo.TDelStorage_List WHERE StockNo='{0}' AND Act_Num > 0", stockNo);
                    cmd = dbHelper.GetSqlStringCommond(strSql);
                    object obj = dbHelper.ExecuteScalar(cmd);
                    int num = int.Parse(obj.ToString());
                    if (num > 0)
                        errMsg.AppendFormat("出库单:{0}有物料已经出库，此时无法再对单据进行人工拣选出库!", stockNo);
                    else
                    {
                        string contents = "线下人工拣选完成";
                        strSql = string.Format(@"UPDATE dbo.TBill_DelStorage SET Small_BillType = 22,Bill_Status = 1,Contents='{1}' WHERE StockNo='{0}'", stockNo, contents);
                        cmd = dbHelper.GetSqlStringCommond(strSql);
                        int n = dbHelper.ExecuteNonQuery(cmd);
                        if (n <= 0)
                            errMsg.AppendFormat("出库单:{0}人工拣选出库失败!");

                        strSql = string.Format(@"UPDATE dbo.TDelStorage_List SET  Act_Num = Num WHERE StockNo='{0}'", stockNo, contents);
                        cmd = dbHelper.GetSqlStringCommond(strSql);
                        n = dbHelper.ExecuteNonQuery(cmd);
                    }
                }
            }

        }
        if (chkCount == 0)
        {
            ShowBox.MessageBox(this.Page, "请选择要处理的单据！");
            return;
        }
        if (string.IsNullOrEmpty(errMsg.ToString()))
        {
            ShowBox.MessageBox(this.Page, "操作成功！");
            bind();
        }
        else
        {
            ShowBox.MessageBox(this.Page, errMsg.ToString());
            //lbMsg.Text = errMsg.ToString();
        }

    }
}